<template>
  <a-modal
    class="common-modal"
    :title="title"
    :footer="null"
    :width="1100"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :maskClosable="false"
    style="top: 5%"
  >
    <a-spin :spinning="confirmLoading">
      <div class="p-20" style="height: calc(50vh + 78px)">
        <a-table
          rowKey="id"
          v-if="visible"
          :loading="loading"
          bordered
          size="small"
          :dataSource="dataSource"
          :columns="columns"
          :pagination="false"
          class="modal-table"
          :scroll="{ y: '50vh', x: 900 }"
          @resizeColumn="handleResizeColumn"
          @change="handleTableChange"
        >
          <template
            #customFilterDropdown="{
              setSelectedKeys,
              selectedKeys,
              confirm,
              clearFilters,
              column,
            }"
          >
            <div style="padding: 8px">
              <!-- <a-input
                ref="searchInput"
                :placeholder="`Search ${column.dataIndex}`"
                :value="selectedKeys[0]"
                style="width: 188px; margin-bottom: 8px; display: block"
                @change="
                  (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
                "
                @pressEnter="
                  handleSearch(selectedKeys, confirm, column.dataIndex, column)
                "
              /> -->
              <a-input-search
                ref="searchInput"
                v-model:value="searchInputValue[column.dataIndex]"
                :placeholder="`${column.title}`"
                style="width: 150px; margin-bottom: 8px; display: block"
                enter-button
                size="small"
                @search="
                  filterSearch(
                    searchInputValue[column.dataIndex],
                    column.dataIndex,
                    column
                  )
                "
              />
              <!-- :options="searchFilterList(column.filters, searchInputValue)" -->
              <a-checkbox-group
                :value="selectedKeys"
                :options="column.filters"
                @change="
                  (checkedValue) =>
                    setSelectedKeys(checkedValue ? checkedValue : [])
                "
              >
                <template #label="scope">
                  <span>{{ scope.text }}</span>
                </template>
              </a-checkbox-group>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  margin-top: 6px;
                "
              >
                <a-button
                  size="small"
                  type="link"
                  :disabled="selectedKeys.length < 1"
                  style="width: 60px"
                  @click="handleReset(clearFilters, column)"
                >
                  {{ $t('common.reset') }}
                </a-button>
                <a-button
                  type="primary"
                  size="small"
                  style="width: 60px"
                  @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
                >
                  {{ $t('common.ok') }}
                </a-button>
              </div>
            </div>
          </template>
          <template #customFilterIcon="{ filtered }">
            <filter-filled
              :style="{ color: filtered ? '#108ee9' : undefined }"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operate'">
              <span class="table-operate-container">
                <span v-if="record.hangParcelStatus">
                  <a-button
                    @click="changeStatus(record, 0)"
                    type="link"
                    class="primary-link"
                    >{{ $t('common.cancel') }}</a-button
                  >
                  <a-divider type="vertical" />
                  <a-button
                    type="link"
                    class="primary-link"
                    @click="editPut(record)"
                    >{{ $t('other.modifiedShelving') }}</a-button
                  >
                </span>
                <a-button
                  v-else
                  @click="changeStatus(record, 1)"
                  type="link"
                  class="primary-link"
                  >{{ $t('other.hitShelves') }}</a-button
                >
              </span>
            </template>
          </template>
        </a-table>
      </div>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
        <a-button
          @click="handleOk"
          v-if="dataSource.length"
          type="primary"
          class="confirm"
          >{{ $t('common.ok') }}</a-button
        >
      </div>
    </a-spin>
    <EditPutawayModal ref="editPutawayModalRef" @ok="getList" />
  </a-modal>
</template>
<script setup>
import { reactive, ref } from "vue";
import { roadmapColumns } from "./prodTimeConfig";
import { filterObj } from "@/utils";
import axios from "@/utils/request";
import { message } from "ant-design-vue";
import { FilterFilled } from "@ant-design/icons-vue";
import EditPutawayModal from "./editPutawayModal";
import { cloneDeep, uniqBy } from "lodash";
import i18n from '@/locales/index'
const { t } = i18n.global
let visible = ref(false);
let confirmLoading = ref(false);
let loading = ref(false);
let title = ref("");
let recordInfo = ref({});
let dataSource = ref([]);
let couponInfo = ref(null); // 原始挂片中数据
let queryParam = ref({});
let stationId = ref(null);
let editPutawayModalRef = ref();
let columns = ref(roadmapColumns);
let isorter = ref({
  field: "",
  order: "",
});
const open = async (record) => {
  stationId.value = record.stationId;
  await getList();
  title.value = `${t('hangManage.road')}${record.stationNo}`;
  recordInfo.value = record;
  visible.value = true;
};
const handleResizeColumn = (w, col) => {
  col.width = w || 0;
}
const getParams = () => {
  let params = [];
  let dataList = [];
  if (couponInfo.value) {
    let originInfo = dataSource.value.filter(
      (i) => i.id == couponInfo.value.id
    )[0];
    let nowCouponInfo = dataSource.value.filter(
      (i) => i.hangParcelStatus == 1 && i.id != couponInfo.value.id
    );
    dataList = nowCouponInfo.length
      ? [originInfo, nowCouponInfo[0]]
      : [originInfo];
  } else {
    dataList = dataSource.value.filter((i) => i.hangParcelStatus == 1);
  }
  dataList.forEach((i) => {
    params.push({
      lineNo: recordInfo.value.hangerLineNo,
      stationId: recordInfo.value.stationId,
      hangParcelStatus: i.hangParcelStatus,
      roadMapId: i.roadMapId,
      scheduleBillId: i.id,
    });
  });
  return params;
};
const handleOk = async () => {
  try {
    let params = getParams();
    confirmLoading.value = true;
    let res = await axios.postAction(
      "/api/hanger/hangerline-realtime/hang-parcel-putaway",
      params
    );
    confirmLoading.value = false;
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'));
      handleCancel();
    }
  } catch {
    confirmLoading.value = false;
    console.log("err");
  }
};
const handleCancel = () => {
  couponInfo.value = null;
  loading.value = false;
  confirmLoading.value = false;
  visible.value = false;
  dataSource.value = [];
  queryParam.value = {};
  isorter.value = {
    field: "",
    order: "",
  };
};
const getQueryParam = () => {
  let params = { ...queryParam.value };
  params.stationId = stationId.value;
  params.sortingFields = isorter.value.field ? [isorter.value] : null;
  return filterObj(params);
};
const getList = async () => {
  try {
    loading.value = true;
    const res = await axios.postAction(
      "/api/hanger/hangerline-realtime/get-online-schedulebill-by-station",
      getQueryParam()
    );
    loading.value = false;
    if (res.success && res.data) {
      dataSource.value = res.data;
      let onHangList = dataSource.value.filter((i) => i.hangParcelStatus == 1);
      couponInfo.value = onHangList.length > 0 ? { ...onHangList[0] } : null;
      initColoum(res.data);
    }
  } catch {
    loading.value = false;
    dataSource.value = [];
  }
};
let initialList = [];
const initColoum = async (data) => {
  // 款号  款名  制单号 床号
  let columnsList = cloneDeep(columns.value);
  columnsList.forEach((i) => {
    let filterList = [
      "moNo",
      "styleNo",
      "color",
      "size",
      "poNo",
      "cutterNo",
      "tailorBill",
    ];
    if (filterList.includes(i.dataIndex)) {
      let ary = data
        .map((el) => ({ text: el[i.dataIndex], value: el[i.dataIndex] }))
        .filter((el) => el.value);
      i.customFilterDropdown = true;
      i.filters = uniqBy(ary, "value");
      i.onFilter = (value, record) =>
        record[i.dataIndex] && record[i.dataIndex].indexOf(value) === 0;
    }
  });
  columns.value = columnsList;
  initialList = cloneDeep(columns.value);
  // console.log(initialList, "--initialList--");
};
// 筛选搜索
const searchInputValue = reactive({});
const searchInput = ref(null);
const filterSearch = (searchInputValue, dataIndex, column) => {
  const filterColumn = initialList.filter((ftm) => {
    return ftm.dataIndex == dataIndex;
  });
  column.filters = filterColumn[0].filters.filter((itm) => {
    return (
      itm.value.toLowerCase().indexOf(searchInputValue?.toLowerCase()) >= 0
    );
  });
};
const handleSearch = (selectedKeys, confirm, dataIndex) => {
  searchInputValue[dataIndex] = null;
  confirm();
};
const handleReset = (clearFilters, column) => {
  searchInputValue[column.dataIndex] = null;
  const filterColumn = initialList.filter((ftm) => {
    return ftm.dataIndex == column.dataIndex;
  });
  column.filters = filterColumn[0].filters;
  clearFilters({
    confirm: true,
  });
};
const handleTableChange = (pagination, filters, sorter) => {
  console.log(filters, "---filters----");
  console.log(sorter, "---sorter----");
  if (Object.keys(sorter).length > 0) {
    isorter.value.field = sorter.field || "";
    isorter.value.order = sorter.order
      ? sorter.order == "ascend"
        ? "asc"
        : "desc"
      : "";
  }
  getList();
};
const changeStatus = (record, status) => {
  if (status) {
    record.hangParcelStatus = status;
    dataSource.value.forEach((i) => {
      if (i.id != record.id) i.hangParcelStatus = 0;
    });
  } else {
    record.hangParcelStatus = status;
  }
};
const editPut = (record) => {
  editPutawayModalRef.value.open(record, recordInfo.value);
};
defineExpose({
  open,
});
</script>
